package com.contactbook.web.controller.account;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.AccountClient;
import com.contactbook.web.service.ContactClient;
import com.contactbook.web.service.GroupClient;
import com.contactbook.web.util.AccountMessage;

import contactbook.model.Account;

public class DeleteAccountController extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	private static final String CONFIRM_DELETE = "Oui";
	private static final String CANCEL_DELETE = "Non";
	
	private AccountClient accountClient;
	private GroupClient groupClient;
	private ContactClient contactClient;
	
	public DeleteAccountController() {
		super();
    	accountClient = new AccountClient();
    	groupClient = new GroupClient();
    	contactClient = new ContactClient();
	}
	
    public void init() throws ServletException {
    	super.init();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		String submit = request.getParameter("submit");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		
		if (account != null) { 
			groupClient.login(account.getLogin(), account.getPassword());
			contactClient.login(account.getLogin(), account.getPassword());
			
			if (submit == null) {
				dispatcher = request.getRequestDispatcher("/delAccount.jsp");
			}
			else if (submit.equals(CONFIRM_DELETE)) {
				AccountMessage message = deleteAccount(request);
				request.setAttribute("message", message);
				dispatcher = request.getRequestDispatcher("/delAccount.jsp");
			}
			else if (submit.equals(CANCEL_DELETE)) {
				dispatcher = request.getRequestDispatcher("/Account");
			}
		
			groupClient.logout();
			contactClient.logout();
		}

		dispatcher.forward(request, response);
	}

	private AccountMessage deleteAccount(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		
		if (account != null) {
			accountClient.login(account.getLogin(), account.getPassword());			
			accountClient.delete();
			session.removeAttribute("account");
			session.invalidate();
			return AccountMessage.ACCOUNT_DELETED_OK;
		}
		return AccountMessage.ACCOUNT_DELETED_FAIL;
	}
	
	public void destroy() {
		super.destroy();
	}
	
}
